package com.btb.adapter.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;

import com.btb.adapter.contract.ActFish;
import com.btb.adapter.contract.ActHero;
import com.btb.adapter.contract.Payment;

@Component
public class Config {

	@Value("${adapter.contract.privateKey}")
	private String privateKey;

	@Value("${web3j.client-address}")
	private String clientAddress;

	@Value("${adapter.contract.chainup.hero}")
	private String chainupHeroAddress;
	
	@Value("${adapter.contract.chainup.fish}")
	private String chainupFishAddress;

	@Value("${adapter.contract.buy.address}")
	private String buyAddress;

	@Bean
	public Credentials credentials() {
		return Credentials.create(privateKey);
	}

	@Bean
	public Web3j web3j() {
//		return Web3j.build(new HttpService(clientAddress));
		return Web3j.build(new HttpSerivceEx(clientAddress));
	}

	@Bean
	public RestTemplate restTemplate() {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(30000);
		requestFactory.setReadTimeout(30000);
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.setRequestFactory(requestFactory);
		return restTemplate;
	}

	/**
	 *   英雄上链合约
	 * @return
	 */
	@Bean
	public ActHero actHero() {
		return new ActHero(chainupHeroAddress, web3j(), credentials());
	}
	/**
	 *   鱼上链合约
	 * @return
	 */
	@Bean
	public ActFish actFish() {
		return new ActFish(chainupFishAddress, web3j(), credentials());
	}

	/**
	 * 	购买合约
	 * @return
	 */
	@Bean
	public Payment payment() {
		return new Payment(buyAddress, web3j(), credentials());
	}
}
